package main

import (
	// "crypto/tls"
	"log"
	"net/http"
	"os"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/filesystem"

	"main/src/utils"
	"main/src/routes"
)

// var GitDirs = utils.FindGitDirectories(os.Getenv("SS_StaticDir"))

func main() {
	utils.LoadEnv()
	GitDirs := utils.FindGitDirectories(os.Getenv("SS_StaticDir"))
	for _, dir := range GitDirs {
		err := utils.UpdateGitRepo(dir)
		if err != nil {
			log.Println(err)
		}
	}

	app := fiber.New()

	app.Use(cors.New(cors.Config{
		AllowOrigins: os.Getenv("SS_AllowOrigins"),
		AllowHeaders: "Origin, Accept",
	}))

	app.Use(os.Getenv("SS_StaticDir")[1:], filesystem.New(filesystem.Config{
		Root:         http.Dir(os.Getenv("SS_StaticDir")),
		Browse:       true,
		Index:        "index.html",
		NotFoundFile: "404.html",
		MaxAge:       3600,
	}))

	routes.Git(app)

	if os.Getenv("SS_TLS") == "ON" {
		// tls_cfg := utils.GetTLSConfig(os.Getenv("SS_DOMAIN"), os.Getenv("SS_CrtDir"))
		// ln, err := tls.Listen("tcp", os.Getenv("SS_PORT"), tls_cfg)
		// if err != nil {
		// 	panic(err)
		// }
		// log.Println(tls_cfg)
		// log.Fatal(app.Listener(ln))
		app.ListenTLS(os.Getenv("SS_PORT"), os.Getenv("SS_TLS_CERT"), os.Getenv("SS_TLS_KEY"))
	} else {
		app.Listen(os.Getenv("SS_PORT"))
	}
}
